package pl.edu.mimuw.mas.agent.behaviour.helicopter.areaassignment;

import jade.content.lang.Codec.CodecException;
import jade.content.onto.OntologyException;
import jade.content.onto.UngroundedException;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;

import java.io.IOException;
import java.util.HashSet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import pl.edu.mimuw.mas.agent.HelicopterAgent;
import pl.edu.mimuw.mas.agent.behaviour.ServerBehaviour;
import pl.edu.mimuw.mas.message.PositionMessage;

/**
 * Zachowanie lidera helikopterów zbierające pozycje helikopterów.
 */
public class ListenPositionBehaviour extends ServerBehaviour {
	private static final long serialVersionUID = 8660639912056314045L;
	private final Logger logger = LoggerFactory.getLogger(getClass());

	private HashSet<PositionMessage> agents;
	private int agentCount;
	
	public ListenPositionBehaviour(HelicopterAgent agent, HashSet<PositionMessage> agents, int agentCount) {
		super(agent);
		MessageTemplate mt = MessageTemplate.and(
				MessageTemplate.MatchConversationId(HelicopterAgent.HELICOPTER_TELL_POSITION_TO_LEADER_CONV),
				MessageTemplate.MatchPerformative(ACLMessage.INFORM)
				);
		setMessageTemplate(mt);
		
		this.agentCount = agentCount;		
		this.agents = agents;
		this.agents.add(new PositionMessage(agent.getAID(), agent.getPosition()));
	}
	
	public boolean doAction(ACLMessage msg, ACLMessage reply) throws UngroundedException, CodecException, OntologyException, UnreadableException, IOException {
		HelicopterAgent ha = (HelicopterAgent) myAgent;
		PositionMessage pm = (PositionMessage) msg.getContentObject();
		agents.add(pm);
		
		logger.debug("{}: Dostalem pozycję agenta {}", myAgent.getName(), pm.getAID().getName());
		ha.log("Dostalem pozycję agenta " + pm.getAID().getName());

		if (agents.size() == agentCount) {
			logger.debug("{}: Dostalem pozycje wszystkich agentów", myAgent.getName());
			ha.log("Dostalem pozycje wszystkich agentów");
			
			stop();
		}

		return false;
	}	
}
